<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="报销编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['paymentCode', validatorRules.paymentCode]"
                placeholder="请输入报销编号"
              ></a-input>
            </a-form-item>
          </a-col>
          <!--<a-col :span="12">-->
          <!--<a-form-item label="提交人" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
          <!--<j-dict-select-tag-->
          <!--:disabled="disableSubmit"-->
          <!--type="list"-->
          <!--v-decorator="['partyId', validatorRules.partyId]"-->
          <!--:trigger-change="true"-->
          <!--dictCode="Person,name,partyId,typeId = EMPLOYEE"-->
          <!--placeholder="请选择提交人"-->
          <!--/>-->
          <!--</a-form-item>-->
          <!--</a-col>-->
          <a-col :span="12">
            <a-form-item label="报销类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                :disabled="disableSubmit"
                type="list"
                v-decorator="['paymentTypeDetailId', validatorRules.paymentTypeDetailId]"
                :trigger-change="true"
                dictCode="DataDictionary,description,dictionaryCode, dictionaryTypeId =REIMBURSEMENT_TYPE"
                placeholder="请选择报销类型"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="成本中心" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                placeholder="请选择成本中心"
                @change="handleCategoryChange"
                v-decorator="['costCode', validatorRules.costCode]"
                :disabled="disableSubmit"
                dict="DataDictionary,description,dictionaryCode, dictionaryTypeId =COSTCENTER_TYPE"
              />
              <!-- <j-category-select
                :disabled="disableSubmit"
                v-decorator="['departmentId', validatorRules.departmentId]"
                pcode="{table:'HrDepartment',txt:'name',key:'departmentId',idField:'id',pidField:'parentId',hasChildField:'hasChild', condition:' parentId = 0'}"
                placeholder="请选择成本中心"
                back="title"
                @change="handleCategoryChange"
              /> -->
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开户行名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['collectionName', validatorRules.collectionName]"
                placeholder="请输入开户行名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收款单位名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['collectionPerson', validatorRules.collectionPerson]"
                placeholder="请输入收款单位名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收款单位账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                :disabled="disableSubmit"
                v-decorator="['collectionCard', validatorRules.collectionCard]"
                placeholder="请输入收款单位账号"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="付款单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                placeholder="请选择付款单位"
                @change="handleCompanyChange"
                :disabled="disableSubmit"
                v-decorator="['paymentCompany', validatorRules.paymentCompany]"
                otherField="sequenceId,dictionaryId"
                dict="DataDictionary,description,dictionaryCode, dictionaryTypeId =COSTPAYMENT_TYPE"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="是否预付款" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                placeholder="请选择是否预付款"
                @change="handleCategoryChange"
                :disabled="disableSubmit"
                v-decorator="['isadvance', validatorRules.isadvance]"
                dict="DataDictionary,description,dictionaryCode, dictionaryTypeId =BOOL_DEFINE"
              />
            </a-form-item>
          </a-col>

          <!--<a-col :span="12">-->
          <!--<a-form-item label="合同" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
          <!--<j-dict-select-tag-->
          <!--type="list"-->
          <!--:disabled="disableSubmit"-->
          <!--v-decorator="['agreementId', validatorRules.agreementId]"-->
          <!--:trigger-change="true"-->
          <!--dictCode="ClmAgreement,name,id, typeId = Purch"-->
          <!--placeholder="请选择合同"-->
          <!--/>-->
          <!--</a-form-item>-->
          <!--</a-col>-->
          <a-col :span="12">
            <a-form-item label="报销日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                :disabled="disableSubmit"
                placeholder="请选择报销日期"
                v-decorator="['expectPaymentDate']"
                :trigger-change="true"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="报销明细项表" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :disabled="disableSubmit"
            :ref="refKeys[0]"
            :tableName="refKeys[0]"
            :loading="clmPaymentItemTable.loading"
            :columns.sync="clmPaymentItemTable.columns"
            :dataSource.sync="clmPaymentItemTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="!disableSubmit"
            :actionButton="!disableSubmit"
            @valueChange="valueChange"
          />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import JCategorySelect from '@/components/jeecg/JCategorySelect'
import { getAction } from '@/api/manage'
export default {
  name: 'ClmReimbursementOrderModal',
  mixins: [JEditableTableMixin],
  components: {
    JUpload,
    JDictSelectTag,
    JSearchSelectTag,
    JDate,
    JCategorySelect,
  },
  data() {
    return {
      disableSubmit: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        paymentCompany: {
          rules: [{ required: true, message: '请选择报销单位!' }],
        },
        collectionCard: {
          rules: [{ required: true, message: '请输入收款单位账号!' }],
        },
        collectionName: {
          rules: [{ required: true, message: '请输入开户行名称!' }],
        },
        collectionPerson: {
          rules: [{ required: true, message: '请输入收款单位名称!' }],
        },
        isadvance: {
          rules: [{ required: true, message: '请选择是否是预付款!' }],
        },
        paymentCode: {
          rules: [{ required: true, message: '请输入报销编码!' }],
        },
        //          partyId: {
        //            rules: [{required: true, message: '请选择提交人!'}],
        //          },
        paymentTypeDetailId: {
          rules: [{ required: true, message: '请选择报销类型!' }],
        },
        costCode: {
          rules: [{ required: true, message: '请选择成本中心!' }],
        },
        //          project: {
        //            rules: [{required: true, message: '请输入所属项目!'}],
        //          },
        //          agreementId: {
        //            rules: [{required: true, message: '请选择合同!'}],
        //          },
      },
      refKeys: ['clmPaymentItem'],
      tableKeys: ['clmPaymentItem'],
      activeKey: 'clmPaymentItem',
      // 报销明细项表
      clmPaymentItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '报销内容',
            key: 'scomment',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [],
          },
          //            {
          //              title: '往来对象',
          //              key: 'objtype',
          //              type: FormTypes.select,
          //              dictCode: 'DataDictionary,description,dictionaryCode, dictionaryTypeId = COSTOBJTYPE1_TYPE',
          //              width: '200px',
          //              placeholder: '请选择${title}',
          //              defaultValue: '',
          //              options:[],
          //              validateRules: [{ required: true, message: '${title}不能为空' }],
          //            },
          //            {
          //              title: '部门',
          //              key: 'dept',
          //              type: FormTypes.select,
          //              dictCode: 'DataDictionary,description,dictionaryCode, dictionaryTypeId = COSTPART_TYPE & parentId = COSTPAYMENT_TYPE99',
          //              width: '200px',
          //              placeholder: '请选择${title}',
          //              defaultValue: '',
          //              options:[],
          //              validateRules: [{ required: true, message: '${title}不能为空' }],
          //            },
          {
            title: '业务员',
            key: 'psndoc',
            type: FormTypes.select,
            dictCode:
              'DataDictionary,description,dictionaryCode, dictionaryTypeId = PSNDOC_TYPE & parentId = COSTPAYMENT_TYPE3',
            width: '200px',
            placeholder: '请选择${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '业务员',
            key: 'psndoc_dictText',
            type: FormTypes.hidden,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [],
          },
          //            {
          //              title: '数量',
          //              key: 'quantity',
          //              type: FormTypes.input,
          //              width: '200px',
          //              placeholder: '请输入${title}',
          //              defaultValue: '',
          //              validateRules: [{required: true, message: '${title}不能为空'}],
          //            },
          {
            title: '费用金额',
            key: 'money',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '无税金额',
            key: 'notaxmoney',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '税率',
            key: 'taxcodeid',
            type: FormTypes.select,
            dictCode: 'DataDictionary,description,dictionaryCode, dictionaryTypeId = COSTRATE_TYPE',
            width: '200px',
            placeholder: '请选择${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '发生时间',
            key: 'paymentdate',
            type: FormTypes.date,
            width: '200px',
            placeholder: '请选择${title}',
            defaultValue: '',
            dataIndex: (text) => {
              return moment(text).format('YYYY-MM-DD')
            },
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '费用说明',
            key: 'remark',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [],
          },
          {
            title: '附件',
            key: 'uploadPath',
            type: FormTypes.file,
            token: true,
            responseName: 'message',
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: '',
          },
          {
            title: '费用项目',
            key: 'costproject',
            type: FormTypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [],
          },
        ],
      },
      url: {
        add: '/online/special/api/createClmPaymentOrder',
        edit: '/online/special/api/updateClmPaymentOrder',
        get: '/online/special/api/getClmPaymentOrder',
        getEnumId: '/online/dict/getDictItems/',
        clmTemplateItem: {
          list: '/online/api/listClmTemplateItemByClmTemplateId',
          deleteBatch: '/online/api/deleteClmTemplateItemByClmTemplateBatch',
        },
      },
    }
  },
  methods: {
    valueChange(values) {
      let row = values.row
      let id = row.id
      let options = values.column.options
      let key = values.column.key
      if (key == 'psndoc') {
        options.forEach((item, index) => {
          if (item.key == row.psndoc) {
            this.$refs.clmPaymentItem.setValues([
              {
                rowKey: id,
                values: {
                  psndoc_dictText: item.text,
                },
              },
            ])
          }
        })
      }
      //有问题.待处理
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    async editAfter() {
      this.model.paymentTypeId = '1'
      let fieldval = pick(
        this.model,
        'paymentCode',
        'partyId',
        'paymentTypeId',
        'paymentTypeDetailId',
        'departmentId',
        'agreementId',
        'costCode',
        'paymentCompany',
        'collectionCard',
        'collectionName',
        'collectionPerson',
        'project',
        'expectPaymentDate',
        'confimCode',
        'isadvance'
      )
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.itemList) {
        this.clmPaymentItemTable.loading = true
        setTimeout(() => {
          this.clmPaymentItemTable.dataSource = JSON.parse(this.model.itemList)
          if (this.model.paymentCompany) {
            let that = this
            getAction(
              this.url.getEnumId +
                'DataDictionary,description,dictionaryId,dictionaryCode=' +
                this.model.paymentCompany +
                '&dictionaryTypeId=COSTPAYMENT_TYPE',
              { otherField: 'dictionaryId' }
            ).then((res2) => {
              if (res2.result.length > 0) {
                let dictionaryId = res2.result[0].dictionaryId
                that.changePartList(dictionaryId, 'N')
              }
            })
          }
          this.clmPaymentItemTable.loading = false
        }, 800)
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      console.log(allValues)
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        itemList: JSON.stringify(allValues.tablesValue[0].values),
      }
      console.log(allValues)
    },
    validateError(msg) {
      if (msg) {
        this.isHandleOk = false
      }
      this.$message.error(msg)
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'paymentCode',
          'partyId',
          'paymentTypeId',
          'paymentTypeDetailId',
          'departmentId',
          'agreementId',
          'costCode',
          'paymentCompany',
          'collectionCard',
          'collectionName',
          'collectionPerson',
          'project',
          'expectPaymentDate',
          'confimCode',
          'isadvance'
        )
      )
    },
    handleCategoryChange(value, backObj) {
      this.form.setFieldsValue(backObj)
    },
    async changePartList(id, isEdit) {
      let column = this.clmPaymentItemTable.columns[1]
      //        const res = await getAction(this.url.getEnumId+'DataDictionary,description,dictionaryId,parentId='+id+'&dictionaryTypeId=PSNDOC_TYPE', {otherField:"dictionaryId"});
      //        if(res.code =="0"){
      //          this.clmPaymentItemTable.columns[1].options = res.result;
      //        }
      //有bug, 刷新不及时
      column.dictCode = 'DataDictionary,description,dictionaryCode, dictionaryTypeId = PSNDOC_TYPE & parentId = ' + id
      this.$refs.clmPaymentItem._loadDictConcatToOptions(column)
    },
    handleCompanyChange(value, backObj) {
      let dictionaryId = backObj.dictionaryId
      this.changePartList(dictionaryId, 'Y')
      this.form.setFieldsValue(backObj)
    },
  },
}
</script>

<style scoped>
</style>
